package com.zodiac.app.szse.sse;

import com.alibaba.fastjson.JSON;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.util.Map;

/**
 * 上交所访问客户端
 */
public class SseClient {

    /**
     * 请求头信息
     */
    public static final Map HEADERS = JSON.parseObject(
            "{" +
                    "'Accept':'*/*'," +
                    "'Accept-Encoding':'gzip,deflate'," +
                    "'Accept-Language':'zh-CN,zh;q=0.9'," +
                    "'Connection':'close'," +
                    "'Host':'query.sse.com.cn'," +
                    "'Referer':'http://kcb.sse.com.cn/renewal/'," +
                    "'User-Agent':'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/71.0.3578.98Safari/537.36'" +
                    "}"
    );

    private Map headers;
    private String url;

    private SseClient(String url) {
        this.url = url;
        this.headers = HEADERS;
    }

    /**
     * 创建实例
     *
     * @param url 请求路径
     * @return
     */
    public static SseClient create(String url) {
        return new SseClient(url);
    }

    /**
     * 请求头
     *
     * @param headers 请求头
     * @return
     */
    public SseClient headers(Map headers) {
        this.headers = headers;
        return this;
    }

    /**
     * 发送请求
     *
     * @param request      请求参数
     * @param responseType 响应类型
     * @param <T>          响应类型
     * @return 响应对象
     */
    public <T> T execute(SseCommonRequest request, Class<T> responseType) {
        final String body = execute(request);
        return JSON.parseObject(body.substring(body.indexOf("(") + 1, body.lastIndexOf(")")), responseType);
    }

    /**
     * 发送请求
     *
     * @param request 请求参数
     * @return 响应体
     */
    public String execute(SseCommonRequest request) {
        try {
            final String url = this.url + "?" + request.toQueryString();
            Connection.Response response = Jsoup.connect(url).headers(this.headers).ignoreContentType(true).execute();
            return response.body();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
